import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfoAPI, getUserProfileAPI } from '@/api/userAPI.js'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)
export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    tokenInfo: {
      token: '',
      refresh_token: ''
    },
    // 用户基本信息
    userInfo: {
    },
    // 用户简介
    userProfile: {}
  },
  mutations: {
    // payload 的格式为{ token, refresh_token }
    updateTokenInfo (state, payload) {
      state.tokenInfo = payload
    },
    updateUserInfo (state, payload) {
      state.userInfo = payload
    },
    // 清空 State 和本地的数据
    cleanState (state) {
      // 1
      state.tokenInfo = {}
      state.userInfo = {}
      // .. 清空用户的简介信息
      state.userProfile = {}
    },
    // 更新用户的简介信息
    updateUserProfile (state, payload) {
      state.userProfile = payload
    }
  },
  modules: {
  },
  // 初始化用户信息
  actions: {
    async initUserInfo (ctx) {
      const { data: res } = await getUserInfoAPI()
      if (res.message === 'OK') {
        ctx.commit('updateUserInfo', res.data)
      }
    },
    // 初始化用户简介的信息
    async initUserProfile (ctx) {
      const { data: res } = await getUserProfileAPI()
      if (res.message === 'OK') {
        ctx.commit('updateUserProfile', res.data)
      }
    }
  },
  getters: {
    avatar (state) {
      return state.userInfo.photo || 'https://img.yzcdn.cn/vant/cat.jpeg'
    }
  }
})
